﻿using AvaVSExt.Attributes;
using AvaVSExt.Helpers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AvaVSExt
{
    public partial class Program
    {
        [VSCommand("font2behind")]
        public static void RunSwitchFont2CodeBehind()
        {
            var info = VSHelper.GetCurrentEditItemInfo();
            if (info is null) return;

            var path = info.ItemFullPath;
            var convertedPath = SwitchFont2CodeBehind.Convert(path);
            if (File.Exists(convertedPath))
            {
                VSHelper.Open(convertedPath);
            }
        }
    }

    public static class SwitchFont2CodeBehind
    {
        public enum FileType
        {
            Unknown, Front, CodeBehind
        }

        static string[] _codeBehinds = new string[] { ".xaml.cs", ".axaml.cs" };
        static string[] _fronts = new string[] { ".xaml", ".axaml" };

        public static string Convert(string file)
        {
            var type = GetType(file);
            if (type.Item2 == FileType.Unknown) return string.Empty;

            var oldArr = Array.Empty<string>();
            var newArr = Array.Empty<string>();

            if (type.Item2 == FileType.Front)
            {
                oldArr = _fronts;
                newArr = _codeBehinds;
            }
            else if (type.Item2 == FileType.CodeBehind)
            {
                oldArr = _codeBehinds;
                newArr = _fronts;
            }

            var index = type.Item1;
            var oldText = oldArr[index];
            var newText = newArr[index];

            return file.Replace(oldText, newText);

        }

        private static (int, FileType) GetType(string file)
        {
            for (int i = 0; i < 2; i++)
            {
                var ext = _codeBehinds[i];
                if (file.EndsWith(ext, StringComparison.OrdinalIgnoreCase))
                {
                    return (i, FileType.CodeBehind);
                }
            }
            for (int i = 0; i < 2; i++)
            {
                var ext = _fronts[i];
                if (file.EndsWith(ext, StringComparison.OrdinalIgnoreCase))
                {
                    return (i, FileType.Front);
                }
            }

            return (-1, FileType.Unknown);
        }
    }
}
